/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.ext.filemanager.builder;

import cn.easyplatform.EasyPlatformWithLabelKeyException;
import cn.easyplatform.lang.Files;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.web.ext.ComponentHandler;
import cn.easyplatform.web.ext.cmez.CMeditor;
import cn.easyplatform.web.ext.filemanager.Filemanager;
import cn.easyplatform.web.ext.filemanager.utils.FileUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.zkoss.image.AImage;
import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zk.ui.metainfo.ComponentInfo;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zkmax.zul.Filedownload;
import org.zkoss.zul.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author Zeta
 * @Version 1.0
 */
public class FilemanagerController extends SelectorComposer<Component> implements EventListener<Event> {

    private Filemanager filemanager;
    private List userList;
    private ComponentHandler dataHandler;
    private String userId;
    private String personPath;
    private String receivePath;
    private String groupPath;

    private Tree tree;
    private Button back;
    private Button upload;
    private Button create;
    private Button paste;
    private Button sortord;
    private Button refresh;
    private Button view;
    private Window window;
    private Label currentFolder;
    private Div showFileDiv;
    private String sort= "DESC";
    private Vlayout currentLayout;
    private Menuitem copy;
    private Menuitem menuPaste;
    private Menuitem cut;
    private Menuitem delete;
    private Menuitem rename;
    private Menuitem param;
    private Menuitem compress;
    private Menuitem uncompress;
    private Menuitem send;
    private Menuitem share;
    private Menuitem download;
    private Bandbox search;

    @Override
    public ComponentInfo doBeforeCompose(Page page, Component parent,ComponentInfo compInfo) {
        return compInfo;
    }

    @Override
    public void doAfterCompose(final Component comp) throws Exception {

        filemanager = (Filemanager) Executions.getCurrent().getArg().get("filemanager");
        userId = (String) Executions.getCurrent().getArg().get("userId");
        userList=(List) Executions.getCurrent().getArg().get("userList");
        dataHandler = (ComponentHandler)Executions.getCurrent().getArg().get("componentHandler");
        personPath = filemanager.getPersonPath()+File.separator+userId+File.separator+"person";
        receivePath = filemanager.getPersonPath()+File.separator+userId+File.separator+"receive";
        groupPath = filemanager.getGroupPath();

        tree = (Tree) comp.getFellow("filemanager_tree_folder");
        tree.addEventListener(Events.ON_SELECT, this);
        back = (Button) comp.getFellow("filemanager_toolbarbutton_back");
        back.addEventListener(Events.ON_CLICK, this);
        upload = (Button) comp.getFellow("filemanager_toolbarbutton_upload");
        upload.addEventListener(Events.ON_UPLOAD, this);
        create = (Button) comp.getFellow("filemanager_toolbarbutton_create");
        create.addEventListener(Events.ON_CLICK, this);
        paste = (Button) comp.getFellow("filemanager_toolbarbutton_paste");
        paste.addEventListener(Events.ON_CLICK, this);
        sortord = (Button) comp.getFellow("filemanager_toolbarbutton_sortord");
        sortord.addEventListener(Events.ON_CLICK, this);
        view = (Button) comp.getFellow("filemanager_toolbarbutton_view");
        view.addEventListener(Events.ON_CLICK, this);
        refresh = (Button) comp.getFellow("filemanager_toolbarbutton_refresh");
        refresh.addEventListener(Events.ON_CLICK, this);
        currentFolder = (Label)comp.getFellow("filemanager_label_currentfolder");
        copy = (Menuitem) comp.getFellow("filemanager_menuitem_copy");
        copy.addEventListener(Events.ON_CLICK, this);
        cut = (Menuitem) comp.getFellow("filemanager_menuitem_cut");
        cut.addEventListener(Events.ON_CLICK, this);
        delete = (Menuitem) comp.getFellow("filemanager_menuitem_delete");
        delete.addEventListener(Events.ON_CLICK, this);
        menuPaste = (Menuitem) comp.getFellow("filemanager_menuitem_paste");
        menuPaste.addEventListener(Events.ON_CLICK, this);
        rename = (Menuitem) comp.getFellow("filemanager_menuitem_rename");
        rename.addEventListener(Events.ON_CLICK, this);
        param = (Menuitem) comp.getFellow("filemanager_menuitem_param");
        param.addEventListener(Events.ON_CLICK, this);
        compress = (Menuitem) comp.getFellow("filemanager_menuitem_compress");
        compress.addEventListener(Events.ON_CLICK, this);
        uncompress = (Menuitem) comp.getFellow("filemanager_menuitem_uncompress");
        uncompress.addEventListener(Events.ON_CLICK, this);
        send = (Menuitem)comp.getFellow("filemanager_menuitem_send");
        send.addEventListener(Events.ON_CLICK, this);
        share = (Menuitem)comp.getFellow("filemanager_menuitem_share");
        share.addEventListener(Events.ON_CLICK, this);
        download = (Menuitem) comp.getFellow("filemanager_menuitem_download");
        download.addEventListener(Events.ON_CLICK, this);
        search = (Bandbox) comp.getFellow("workbenchTable_bandbox_search");
        search.addEventListener(Events.ON_OK, this);
        search.addEventListener(Events.ON_OPEN, this);
        showFileDiv = (Div) comp.getFellow("filemanager_div_showfile");
        window = (Window)comp;
        init();
    }

    @Override
    public void onEvent(Event event) throws Exception {
        if (event.getTarget().equals(tree)){
            Treeitem ti = tree.getSelectedItem();
            String type = (String) ti.getAttribute("type");
            File file = ti.getValue();
            selectedItem(file,type);
        } else if(event.getTarget().equals(back)){
            File file = (File)currentFolder.getAttribute("file");
            if(file!=null) {
                showFileDiv.getChildren().clear();
                Object obj = (tree.getSelectedItem()).getParent().getParent();
                if(obj instanceof Treeitem) {
                    Treeitem ti = (Treeitem) obj;
                    File parent = ti.getValue();
                    currentFolder.setValue("文件夹名称：" + parent.getName());
                    currentFolder.setAttribute("file", parent);
                    tree.setSelectedItem(ti);
                    showSelectFolder(ti);
                    if (parent != null) {
                        createFileGroup(parent,"DESC");
                    }
                }else{
                    currentFolder.setValue("文件夹名称：网络硬盘");
                }
            }
        }else if(event.getTarget().equals(upload)){
            UploadEvent evt = (UploadEvent) event;
            File file = (File) currentFolder.getAttribute("file");
            if(file==null){
                Messagebox.show("请指定父级文件夹。","错误",Messagebox.OK, Messagebox.INFORMATION);
                return;
            }
            copyMediaToFile(file.getAbsolutePath(), evt.getMedia());
        }else if(event.getTarget().equals(create)){
            createFolder();
        }else if(event.getTarget().equals(refresh)){
            refreshAll();
        }else if(event.getTarget().equals(sortord)){
            changeSortord();
        }else if(event.getTarget().equals(paste)){
            pasteFile();
        }else if(event.getTarget().equals(view)){
            if(currentLayout==null){
                return;
            }
            File file = (File) currentLayout.getAttribute("file");
            if(file!=null && !file.isDirectory()) {
                showFile(file);
            }else{
                Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            }
        }else if(event.getTarget().equals(copy)){
            if(currentLayout==null){
                return;
            }
            File file = (File) currentLayout.getAttribute("file");
            if(file!=null){
                paste.setAttribute("copyFile",file);
                paste.setAttribute("type","copy");
            }else{
                Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            }
        }else if(event.getTarget().equals(menuPaste)){
            pasteFile();
        }else if(event.getTarget().equals(cut)){
            if(currentLayout==null){
                return;
            }
            File file = (File) currentLayout.getAttribute("file");
            if(file!=null){
                paste.setAttribute("copyFile",file);
                paste.setAttribute("type","cut");
            }else{
                Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            }
        }else if(event.getTarget().equals(delete)){
            if(currentLayout==null){
                return;
            }
            File file = (File) currentLayout.getAttribute("file");
            if(file!=null){
                boolean success = FileUtil.deleteDir(file);
                if (success) {
                    refreshAll();
                }
            }else{
                Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            }
        }else if(event.getTarget().equals(rename)){
            renameFile();
        }else if(event.getTarget().equals(param)){
            showFileParam();
        }else if(event.getTarget().equals(compress)){
            compressFile();
        }else if(event.getTarget().equals(uncompress)){
            uncompressFile();
        }else if(event.getTarget().equals(send)){
            sendFile();
        }else if(event.getTarget().equals(share)){
            shareFile();
        }else if(event.getTarget().equals(download)){
            downloadFile();
        }else if(event.getTarget().equals(search)){
            String str = search.getValue().trim();
            searchFile(str);
        }else if (event.getTarget() instanceof A) {
            Vlayout vlayout = (Vlayout) event.getTarget().getParent().getParent();
            if (currentLayout == null) {
                currentLayout = vlayout;
                currentLayout.setSclass("ui-div-selected");
            } else if(currentLayout != vlayout){
                vlayout.setSclass("ui-div-selected");
                currentLayout.setSclass("ui-div-normal");
                currentLayout = vlayout;
            }
        }
    }


    /**
     * 初始化
     */
    private void init() {

        if(Strings.isBlank(userId))
            //throw new EasyPlatformWithLabelKeyException("The userId is not defined.");
        if(Strings.isBlank(filemanager.getPersonPath()))
            throw new EasyPlatformWithLabelKeyException("The privatePath is not configured.");
        if (Strings.isBlank(filemanager.getGroupPath()))
            throw new EasyPlatformWithLabelKeyException("The groupPath is not configured.");

        FileUtil.mkdirForNoExists(personPath);
        FileUtil.mkdirForNoExists(receivePath);
        FileUtil.mkdirForNoExists(groupPath);

        //创建树结构
        Treechildren td = new Treechildren();
        Treeitem person = addTreeitem("个人文件夹","~./js/filemanager/image/folder_user.png");
        Treeitem receive = addTreeitem("收到的文件","~./js/filemanager/image/folder_database.png");
        Treeitem group = addTreeitem("部门文件夹","~./js/filemanager/image/folder_feed.png");
        person.setParent(td);
        receive.setParent(td);
        group.setParent(td);
        td.setParent(tree);
        addTreeNode(personPath,person,"person");
        addTreeNode(receivePath,receive,"receive");
        addTreeNode(groupPath,group,"group");
        /*for(String str : shareList) {
            addTreeNode(str, share);
        }
        sort= "DESC";*/
    }

    /**
     * 创建第一级子节点
     * @param name
     * @param img
     * @return
     */
    private Treeitem addTreeitem(String name,String img) {
        Treeitem ti = new Treeitem();
        ti.setOpen(false);
        ti.setSelectable(true);
        Treerow tr = new Treerow();
        Treecell tc = new Treecell();
        tc.setSclass("tree-center tree-margin");
        tc.setImage(img);
        Label lab = new Label(name);
        lab.setParent(tc);
        tc.setParent(tr);
        tr.setParent(ti);
        return ti;
    }

    /**
     * 创建所有子节点
     * @param path
     * @param parent
     */
    private void addTreeNode(String path,Component parent,String type) {
        File root = new File(FilenameUtils.normalize(path));
        parent.setAttribute("type",type);
        ((Treeitem)parent).setValue(root);
        File[] files = root.listFiles((root1, name) -> !name.startsWith("."));
        if (files != null) {
            Treechildren td = new Treechildren();
            Arrays.sort(files, (o1, o2) -> o1.isDirectory() ? 1 : -1);
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                if (file.isDirectory()) {
                    Treeitem ti = new Treeitem();
                    ti.setOpen(false);
                    ti.setSelectable(true);
                    Treerow tr = new Treerow();
                    Treecell tc = new Treecell();
                    Label name = new Label(file.getName());
                    name.setParent(tc);
                    tc.setParent(tr);
                    tc.setImage("~./js/filemanager/image/folder.png");
                    tc.setSclass("tree-center tree-margin");
                    tr.setParent(ti);
                    ti.setParent(td);
                    td.setParent(parent);
                    //添加文件夹类型避免相同路径文件产生覆盖
                    currentFolder.setAttribute(type+"-"+file.getPath(),ti);
                    addTreeNode(file.getAbsolutePath(),ti,type);
                }else{
                    td.setParent(parent);
                }
            }
        }
    }


    /**
     * 树选中事件
     * @param file
     */
    private void selectedItem(File file,String type) {
        showFileDiv.getChildren().clear();
        if (file != null && file.exists()) {
            currentFolder.setValue("文件夹名称："+file.getName());
            currentFolder.setAttribute("file",file);
            currentFolder.setAttribute("type",type);
            createFileGroup(file,"DESC");
        }
        currentLayout = null;
    }

    /**
     * 创建文件图标内容
     * @param parent
     */
    private void createFileGroup(File parent,String sortType){
        if(parent.isDirectory()) {
            File[] files = parent.listFiles((root1, name) -> !name.startsWith("."));
            if (sortType.equals("DESC")) {
                Arrays.sort(files, (o1, o2) -> o1.isDirectory() ? -1 : 1);
                sort = "DESC";
            } else {
                Arrays.sort(files, (o1, o2) -> o1.isDirectory() ? 1 : -1);
                sort = "ASC";
            }
            for (int i = 0; i < files.length; i++) {
                createFileicon(files[i]);
            }
        }else{
            createFileicon(parent);
        }
    }

    /**
     * 创建图标内容具体方法
     * @param file
     */
    private void createFileicon(File file){
        String filetype = FilenameUtils.getExtension(file.getName()).toLowerCase();
        Vlayout vlayout = new Vlayout();
        vlayout.setSpacing("0");
        vlayout.setHeight("100px");
        vlayout.setWidth("100px");
        vlayout.setStyle("text-align: center;verticle-align:middle;");
        vlayout.setSclass("ui-div-normal");
        vlayout.addEventListener(Events.ON_CLICK, this);
        vlayout.setAttribute("name", file.getName());
        vlayout.setAttribute("file", file);

        Div div = new Div();
        div.setSclass("ui-div-center-parent");
        div.setHeight("45px");
        A icon = new A();
        icon.setStyle("text-decoration: none;");
        icon.setSclass("icon-style");
        icon.addEventListener(Events.ON_DOUBLE_CLICK, event1 -> {
            if (file.isDirectory()) {
                currentFolder.setValue("文件夹名称：" + file.getName());
                currentFolder.setAttribute("file", file);
                String type = (String) currentFolder.getAttribute("type");
                Treeitem ti = (Treeitem) currentFolder.getAttribute(type+"-"+file.getPath());
                if (ti != null) {
                    showSelectFolder(ti);
                    tree.setSelectedItem(ti);
                }
                selectedItem(file,type);
                currentLayout = null;
            } else {
                showFile(file);
            }
        });
        icon.addEventListener(Events.ON_CLICK, this);
        if (file.isDirectory()) {
            icon.setIconSclass("icon iconfont icon-file-s-");
        } else if (filetype.equals("png") || filetype.equals("jpg")) {
            icon.setIconSclass("icon iconfont icon-file-b-6");
        } else if (filetype.equals("ppt")) {
            icon.setIconSclass("icon iconfont icon-file-b-4");
        } else if (filetype.equals("doc") || filetype.equals("docx")) {
            icon.setIconSclass("icon iconfont icon-file-b-3");
        } else if (filetype.equals("avi")) {
            icon.setIconSclass("icon iconfont icon-file-b-10");
        } else if (filetype.equals("json")) {
            icon.setIconSclass("icon iconfont icon-JSON");
        } else if (filetype.equals("html")) {
            icon.setIconSclass("icon iconfont icon-HTML");
        } else if (filetype.equals("css")) {
            icon.setIconSclass("icon iconfont icon-CSS");
        } else if (filetype.equals("js")) {
            icon.setIconSclass("icon iconfont icon-JS");
        } else if (filetype.equals("zip")) {
            icon.setIconSclass("icon iconfont icon-file-b-4");
        } else {
            icon.setIconSclass("icon iconfont icon-file-b-8");
        }
        Label lb = new Label();
        lb.setValue(file.getName());
        lb.setStyle("font-size:12px;border-radius: 14px;padding: 2px 8px;");
        icon.setParent(div);
        div.setParent(vlayout);
        lb.setParent(vlayout);
        vlayout.setParent(showFileDiv);
    }

    /**
     * 打开选中文件的所有父级文件夹
     * @param obj
     */
    private void showSelectFolder(Object obj){
        if(obj instanceof Treeitem) {
            Treeitem ti = (Treeitem) obj;
            ti.setOpen(true);
            showSelectFolder(ti.getParent().getParent());
        }
    }

    /**
     * 修改排序方式
     */
    private void changeSortord(){
        if(currentLayout==null){
            return;
        }
        showFileDiv.getChildren().clear();
        File file = (File)currentFolder.getAttribute("file");
        if(file!=null) {
            if (sort.equals("DESC")) {
                createFileGroup(file,"ASC");
            } else {
                createFileGroup(file, "DESC");
            }
        }
    }

    /**
     * 上传文件
     * @param dirPath
     * @param media
     */
    private void copyMediaToFile(String dirPath, Media media) {
        try {
            String mediaPath = dirPath + File.separator + media.getName();
            byte[] bytes = null;
            try {
                bytes = media.getByteData();
            } catch (IllegalStateException e) {
                bytes = media.getStringData().getBytes();
            }
            FileUtils.copyInputStreamToFile(new ByteArrayInputStream(bytes), new File(mediaPath));
            Messagebox.show("上传成功。","成功",Messagebox.OK, Messagebox.INFORMATION);
        } catch (IOException e) {
            Messagebox.show("上传失败。","错误",Messagebox.OK, Messagebox.INFORMATION);
            e.printStackTrace();
        }
    }

    /**
     * 新建文件夹
     */
    private void createFolder() {
        if(currentLayout==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        File file= (File) currentFolder.getAttribute("file");
        if(file==null){
            Messagebox.show("请指定父级文件夹。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        String path = file.getAbsolutePath();
        Window win = new Window();
        win.setTitle("新建文件夹");
        win.setSizable(true);
        win.setClosable(true);
        win.setMaximizable(true);
        win.setWidth("400px");
        win.setHeight("220px");
        win.setPosition("top,center");
        win.setBorder("normal");
        win.setParent(window);
        Div editDiv = new Div();
        editDiv.setWidth("100%");
        editDiv.setHeight("50%");
        editDiv.setSclass("ui-div-center-parent");
        Label lb = new Label("请输入文件夹名称：");
        Textbox folderName = new Textbox();
        lb.setParent(editDiv);
        folderName.setParent(editDiv);
        Div operateDiv = new Div();
        operateDiv.setWidth("100%");
        operateDiv.setHeight("50%");
        operateDiv.setSclass("ui-div-center-parent");
        Button confirm = new Button();
        confirm.setLabel("确定");
        confirm.setStyle("margin-right:30px;width:100px");
        confirm.addEventListener(Events.ON_CLICK, event1 -> {
            String name = folderName.getValue().trim();
            if(!Strings.isBlank(name)){
                FileUtil.mkdirForNoExists(path+File.separator+name);
                win.detach();
                refreshAll();
            }else{
                Messagebox.show("输入文件名为空","错误",Messagebox.OK, Messagebox.INFORMATION);
            }
        });
        Button cancel = new Button();
        cancel.setLabel("取消");
        cancel.addEventListener(Events.ON_CLICK, event1 -> {
            win.detach();
        });
        cancel.setStyle("margin-left:30px;width:100px");
        confirm.setParent(operateDiv);
        cancel.setParent(operateDiv);
        editDiv.setParent(win);
        operateDiv.setParent(win);
        win.doOverlapped();
    }

    /**
     * 刷新
     */
    private void refreshAll() {
        if(currentLayout==null){
            return;
        }
        tree.getTreechildren().detach();
        showFileDiv.getChildren().clear();
        init();
        File file = (File) currentFolder.getAttribute("file");
        String type = (String) currentFolder.getAttribute("type");
        Treeitem ti = (Treeitem) currentFolder.getAttribute(type+"-"+file.getPath());
        if(ti!=null){
            showSelectFolder(ti);
            tree.setSelectedItem(ti);
        }
        selectedItem(file,type);
    }


    /**
     * 重命名
     */
    private void renameFile() {
        if(currentLayout==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        File file= (File) currentLayout.getAttribute("file");
        if(file==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        Window win = new Window();
        win.setTitle("文件重命名");
        win.setSizable(true);
        win.setClosable(true);
        win.setMaximizable(true);
        win.setWidth("400px");
        win.setHeight("220px");
        win.setPosition("top,center");
        win.setBorder("normal");
        win.setParent(window);
        Div hintDiv = new Div();
        hintDiv.setWidth("100%");
        hintDiv.setHeight("35%");
        hintDiv.setSclass("ui-div-center-parent");
        Label lb = new Label("文件原名称："+file.getName());
        lb.setParent(hintDiv);
        Div editDiv = new Div();
        editDiv.setWidth("100%");
        editDiv.setHeight("35%");
        editDiv.setSclass("ui-div-center-parent");
        Label lbs = new Label("请输入新名称：");
        Textbox folderName = new Textbox();
        folderName.setWidth("100px");
        lbs.setParent(editDiv);
        folderName.setParent(editDiv);
        Div operateDiv = new Div();
        operateDiv.setWidth("100%");
        operateDiv.setHeight("30%");
        operateDiv.setSclass("ui-div-center-parent");
        Button confirm = new Button();
        confirm.setLabel("确定");
        confirm.setStyle("margin-right:30px;width:100px");
        confirm.addEventListener(Events.ON_CLICK, event1 -> {
            String name = folderName.getValue().trim();
            if(!Strings.isBlank(name)){
                FileUtil.renameFile(file,name);
                win.detach();
                refreshAll();
            }else{
                Messagebox.show("输入文件名为空","错误",Messagebox.OK, Messagebox.INFORMATION);
            }
        });
        Button cancel = new Button();
        cancel.setLabel("取消");
        cancel.addEventListener(Events.ON_CLICK, event1 -> {
            win.detach();
        });
        cancel.setStyle("margin-left:30px;width:100px");
        confirm.setParent(operateDiv);
        cancel.setParent(operateDiv);
        hintDiv.setParent(win);
        editDiv.setParent(win);
        operateDiv.setParent(win);
        win.doOverlapped();
    }

    /**
     * 属性
     */
    private void showFileParam(){
        if(currentLayout==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        File file= (File) currentLayout.getAttribute("file");
        if(file==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        Window win = new Window();
        win.setTitle("文件属性");
        win.setSizable(true);
        win.setClosable(true);
        win.setMaximizable(true);
        win.setWidth("400px");
        win.setHeight("220px");
        win.setPosition("top,center");
        win.setBorder("normal");
        win.setParent(window);
        Div nameDiv = new Div();
        nameDiv.setWidth("100%");
        nameDiv.setHeight("20%");
        nameDiv.setSclass("ui-div-center-parent");
        Label name = new Label("文件夹名称："+file.getName());
        name.setParent(nameDiv);
        Div pathDiv = new Div();
        pathDiv.setWidth("100%");
        pathDiv.setHeight("20%");
        pathDiv.setSclass("ui-div-center-parent");
        Label path = new Label("文件夹路径："+file.getAbsolutePath());
        path.setParent(pathDiv);
        Div lengthDiv = new Div();
        lengthDiv.setWidth("100%");
        lengthDiv.setHeight("20%");
        lengthDiv.setSclass("ui-div-center-parent");
        Long len=0L;
        if(file.isDirectory()){
            len=FileUtil.getFolderLength(file,len);
        }else {
            len = file.length();
        }
        Label length = new Label("文件夹大小："+(len/1024)+" KB( "+len+" 字节 )");
        length.setParent(lengthDiv);
        Div timeDiv = new Div();
        timeDiv.setWidth("100%");
        timeDiv.setHeight("20%");
        timeDiv.setSclass("ui-div-center-parent");
        Date date = new Date(file.lastModified());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Label time = new Label("文件夹最后修改时间："+sdf.format(date));
        time.setParent(timeDiv);
        Div operateDiv = new Div();
        operateDiv.setWidth("100%");
        operateDiv.setHeight("20%");
        operateDiv.setSclass("ui-div-center-parent");
        Button confirm = new Button();
        confirm.setLabel("确定");
        confirm.setStyle("margin-right:30px;width:100px");
        confirm.addEventListener(Events.ON_CLICK, event1 -> {
            win.detach();
        });
        confirm.setParent(operateDiv);
        nameDiv.setParent(win);
        pathDiv.setParent(win);
        lengthDiv.setParent(win);
        timeDiv.setParent(win);
        operateDiv.setParent(win);
        win.doOverlapped();
    }

    /**
     * 压缩
     */
    private void compressFile(){
        if(currentLayout==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        File file= (File) currentLayout.getAttribute("file");
        if(file==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        File parentfile = (File) currentFolder.getAttribute("file");
        if(file==null){
            Messagebox.show("请指定父级文件夹。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        String destFilePath = parentfile.getAbsolutePath() + File.separator +
                file.getName().substring(0,file.getName().indexOf(".")) + ".zip";

        if(file.isDirectory()) {
            FileUtil.compress(file.getAbsolutePath(),destFilePath,false);
        }else{
            FileUtil.compress(file.getAbsolutePath(),destFilePath,true);
        }
        refreshAll();
    }

    /**
     * 解压
     */
    private void uncompressFile(){
        if(currentLayout==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        File file= (File) currentLayout.getAttribute("file");
        if(file==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        String type = FilenameUtils.getExtension(file.getName()).toLowerCase();
        if(!type.equals("zip")){
            Messagebox.show("文件类型错误，只能解压zip文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        File parentfile = (File) currentFolder.getAttribute("file");
        if(file==null){
            Messagebox.show("请指定父级文件夹。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        FileUtil.unZip(file, parentfile.getAbsolutePath());
        refreshAll();
    }

    /**
     * 显示文件内容
     * @param file
     * @throws Exception
     */
    private void showFile(File file) throws Exception{
        Div editDiv ;
        String type = FilenameUtils.getExtension(file.getName()).toLowerCase();
        if (type.equals("jpg") || type.equals("png") || type.equals("jpeg") || type.equals("gif")) {
            editDiv = new Div();
            Image image = new Image();
            BufferedImage img = ImageIO.read(file);
            image.setHeight(img.getHeight() + "px");
            image.setWidth(img.getWidth() + "px");
            image.setZclass("border rounded mx-auto d-block");
            /*if (img.getWidth() > img.getHeight()) {
                if (img.getHeight() > 140) {
                    pics.setHeight("140px");
                    pics.setWidth(img.getWidth() * 140 / img.getHeight() + "px");
                }else{
                    pics.setHeight(img.getWidth());
                    pics.setWidth(img.getWidth() * img.getWidth() / img.getHeight() + "px");
                }
            } else {
                if (img.getWidth() > 160) {
                    pics.setWidth("160px");
                    pics.setHeight(img.getHeight() * 160 / img.getWidth() + "px");
                }else{
                    pics.setHeight(img.getHeight());
                    pics.setWidth(img.getWidth() * img.getWidth() / img.getHeight() + "px");
                }
            }*/
            image.setStyle("border:2px dashed #e6e6e6;border-radius:10px;display: inline;justify-content:center;align-items:Center;max-height: 350px;max-width: 700px;");
            try {
                image.setContent(new AImage(file.getName(), new FileInputStream(file)));
            } catch (IOException e) {
                Messagebox.show("图片显示出错。","错误",Messagebox.OK, Messagebox.INFORMATION);
                e.printStackTrace();
            }
            image.setParent(editDiv);
        } else if (type.contains("css") || type.equals("js") || type.equals("json") || type.equals("zul")
                ||type.equals("html")||type.equals("java")) {
            editDiv = new Div();
            CMeditor editor = new CMeditor();
            editor.setHflex("1");
            editor.setVflex("1");
            editor.setFoldGutter(true);
            editor.setAutoCloseTags(true);
            editor.setLineNumbers(true);
            editor.setCollapse(true);
            editor.setBorder("none");
            editor.setReadonly(true);
            editor.setDisabled(true);
            editor.setValue(FileUtils.readFileToString(file, "UTF-8"));
            editor.addEventListener(Events.ON_CHANGE, this);
            editor.setParent(editDiv);
            if (type.equals("js"))
                editor.setMode("javascript");
            else if (type.equals("zul"))
                editor.setMode("eppage");
            else if (type.equals("html"))
                editor.setMode("text/html");
            else if (type.equals("java"))
                editor.setMode("text/x-java");
            else editor.setMode(type);
        }else{
            Messagebox.show("该文件不支持预览，请下载查看。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        editDiv.setWidth("100%");
        editDiv.setHeight("90%");
        editDiv.setSclass("ui-div-center-parent");
        Window win = new Window();
        win.setTitle("文件显示");
        win.setSizable(true);
        win.setClosable(true);
        win.setMaximizable(true);
        win.setWidth("800px");
        win.setHeight("500px");
        win.setPosition("top,center");
        win.setBorder("normal");
        win.setParent(window);
        Div operateDiv = new Div();
        operateDiv.setWidth("100%");
        operateDiv.setHeight("10%");
        operateDiv.setSclass("ui-div-center-parent");
        Button confirm = new Button();
        confirm.setLabel("确定");
        confirm.setStyle("margin-right:30px;width:100px");
        confirm.addEventListener(Events.ON_CLICK, event1 -> {
            win.detach();
        });
        confirm.setParent(operateDiv);
        editDiv.setParent(win);
        operateDiv.setParent(win);
        win.doOverlapped();
    }

    /**
     * 粘贴
     */
    private void pasteFile(){
        File file = (File) paste.getAttribute("copyFile");
        if(file!=null){
            String type = (String) paste.getAttribute("type");
            File parent = (File) currentFolder.getAttribute("file");
            if(parent==null){
                Messagebox.show("请指定父级文件夹。","错误",Messagebox.OK, Messagebox.INFORMATION);
                return;
            }
            boolean success = FileUtil.saveFolderByFile(file, parent.getAbsolutePath());
            if (success) {
                if(type.equals("cut")) {
                    FileUtil.deleteDir(file);
                }
                paste.removeAttribute("copyFile");
                refreshAll();
            }
        }

    }

    /**
     * 查找文件
     * @param str
     */
    private void searchFile(String str) {
        showFileDiv.getChildren().clear();
        File file = (File)currentFolder.getAttribute("file");
        if(!Strings.isBlank(str)&&file!=null) {
            File[] files = file.listFiles((root1, name) -> !name.startsWith("."));
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().contains(str)) {
                    createFileicon(files[i]);
                }
            }
        }else if(file!=null){
            createFileGroup(file,"DESC");
        }
    }

    /**
     * 下载文件
     */
    private void downloadFile(){
        if(currentLayout==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        File file = (File) currentLayout.getAttribute("file");
        if(file!=null && !file.isDirectory()) {
            try {
                Filedownload.save(file, Files.getContentType(FilenameUtils.getExtension(file.getName())));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }else{
            Messagebox.show("只允许下载文件，请重新选择。","成功",Messagebox.OK, Messagebox.INFORMATION);
        }
    }

    /**
     * 发送文件
     */
    private void sendFile(){
        if(currentLayout==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        File file= (File) currentLayout.getAttribute("file");
        if(file==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        Window win = new Window();
        win.setTitle("文件分享");
        win.setSizable(true);
        win.setClosable(true);
        win.setMaximizable(true);
        win.setWidth("500px");
        win.setHeight("400px");
        win.setPosition("top,center");
        win.setBorder("normal");
        win.setParent(window);
        Div listDiv = new Div();
        listDiv.setWidth("100%");
        listDiv.setHeight("90%");
        listDiv.setSclass("ui-div-center-parent");
        Listbox listbox = new Listbox();
        listbox.setVflex("1");
        listbox.setHflex("1");
        listbox.setMold("paging");
        listbox.setMultiple(true);
        listbox.setCheckmark(true);
        listbox.setParent(listDiv);
        Listhead listhead = new Listhead();
        listhead.setSizable(true);
        listhead.setParent(listbox);
        Listheader operateheader = new Listheader();
        operateheader.setWidth("50px");
        operateheader.setParent(listhead);
        Listheader idheader = new Listheader();
        idheader.setLabel("ID");
        idheader.setWidth("100px");
        idheader.setParent(listhead);
        Listheader nameheader = new Listheader();
        nameheader.setLabel("姓名");
        nameheader.setHflex("1");
        nameheader.setParent(listhead);

        if(userList!=null){
            for (Object user : userList) {
                Listitem li = new Listitem();
                li.setValue((String)((Object[])user)[0]);
                Listcell checkmark=new Listcell("");
                checkmark.setStyle("text-align: center;");
                li.appendChild(checkmark);
                li.appendChild(new Listcell((String)((Object[])user)[0]));
                li.appendChild(new Listcell((String)((Object[])user)[1]));
                li.setParent(listbox);
            }
        }
        Div operateDiv = new Div();
        operateDiv.setWidth("100%");
        operateDiv.setHeight("10%");
        operateDiv.setSclass("ui-div-center-parent");
        Button confirm = new Button();
        confirm.setLabel("确定");
        confirm.setStyle("margin-left:30px;width:100px");
        confirm.addEventListener(Events.ON_CLICK, event1 -> {
            List<String> list = new ArrayList<>();
            for(Listitem sel : listbox.getItems()){
                if (!sel.isSelected())
                    continue;
                if (sel.getValue() != null) {
                    String userId = (String)sel.getValue();
                    if(!Strings.isBlank(userId)) {
                        String targetPath = filemanager.getPersonPath()+File.separator+userId+File.separator+"receive";
                        FileUtil.mkdirForNoExists(targetPath);
                        try {
                            if(file.isDirectory()) {
                                targetPath = targetPath + File.separator + file.getName();
                            }
                            FileUtil.copyDir(file.getAbsolutePath(),targetPath);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        list.add(userId);
                    }else{
                        Messagebox.show("指定用户有误，请确认用户信息。","错误",Messagebox.OK, Messagebox.INFORMATION);
                        list.clear();
                        break;
                    }
                }
            }
            String targetId = JSON.toJSONString(list);
            String path = file.getAbsolutePath().replaceAll("\\\\","/");
            if(!Strings.isBlank(targetId)) {
                String userQuery = "insert into sys_file_info (userId,targetId,fileName,filePath,fileDesc,createDate) values " +
                        "('" + userId + "','"+targetId+ "','"+file.getName()+ "','"+path+ "','备注','"+new Timestamp((new Date()).getTime())+ "')";
                System.out.println(userQuery);
                dataHandler.executeUpdate0(filemanager.getDbId(), userQuery);
            }
            win.detach();
            Messagebox.show("发送文件成功。","成功",Messagebox.OK, Messagebox.INFORMATION);
            refreshAll();
        });
        Button cancel = new Button();
        cancel.setLabel("取消");
        cancel.addEventListener(Events.ON_CLICK, event1 -> {
            win.detach();
        });
        cancel.setStyle("margin-right:30px;width:100px");
        cancel.setParent(operateDiv);
        confirm.setParent(operateDiv);
        listDiv.setParent(win);
        operateDiv.setParent(win);
        win.doOverlapped();
    }

    /**
     * 分享文件
     */
    private void shareFile(){
        if(currentLayout==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        File file= (File) currentLayout.getAttribute("file");
        if(file==null){
            Messagebox.show("请指定文件。","错误",Messagebox.OK, Messagebox.INFORMATION);
            return;
        }
        try {
            FileUtil.copyDir(file.getAbsolutePath(),groupPath+File.separator+userId);
            String targetId = "部门文件夹";
            String path = file.getAbsolutePath().replaceAll("\\\\","/");
            if(!Strings.isBlank(targetId)) {
                String userQuery = "insert into sys_file_info (userId,targetId,fileName,filePath,fileDesc,createDate) values " +
                        "('" + userId + "','"+targetId+ "','"+file.getName()+ "','"+path+ "','备注','"+new Timestamp((new Date()).getTime())+ "')";
                System.out.println(userQuery);
                dataHandler.executeUpdate0(filemanager.getDbId(), userQuery);
            }
            Messagebox.show("分享到部门文件夹成功。","成功",Messagebox.OK, Messagebox.INFORMATION);
            refreshAll();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
